import { ValidationErrors } from '@angular/forms';
import { EzForm } from '../components/ez-form';
import { EzFormControl } from '../components/ez-form-control';
import { EzFormGroup } from '../components/ez-form-group';

export const REGEXP_EMAIL: RegExp = /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/;

// tslint:disable-next-line: max-line-length
export const REGEXP_PHONE_NUMBER: RegExp = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/;

export const REGEXP_IDCARD: RegExp = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;

export type EzFormValidatorFn = (control: EzFormControl, group: EzFormGroup, form: EzForm) => null | ValidationErrors;

export class EzFormValidators {
  static nullValidator(control: EzFormControl, group: EzFormGroup, form: EzForm): null | ValidationErrors {
    return null;
  }

  static required(control: EzFormControl, group: EzFormGroup, form: EzForm): null | ValidationErrors {
    const value = control.getValue();
    if ((!value && value !== false && value !== 0) || (Array.isArray(value) && value.length === 0)) {
      return { required: true };
    }
    return null;
  }

  static maxlength(maxlength: number = Infinity, error: string = null) {
    const fn = (control: EzFormControl, group: EzFormGroup, form: EzForm) => {
      if (control.getValue() && control.getValue().length > maxlength) {
        return { maxlength: error || `长度不能超过${maxlength}个字符` };
      }
      return null;
    };
    return fn;
  }

  static minlength(minlength: number = -Infinity, error: string = null) {
    const fn = (control: EzFormControl, group: EzFormGroup, form: EzForm) => {
      if (control.getValue() && control.getValue().length < minlength) {
        return { minlength: error || `长度不能少于${minlength}个字符` };
      }
      return null;
    };
    return fn;
  }

  static regex(regExp: RegExp | string, error: string = null) {
    if (!regExp) {
      const nullFn = () => null;
      return nullFn;
    }
    const reg = regExp instanceof RegExp ? regExp : new RegExp(regExp);
    const fn = (control: EzFormControl, group: EzFormGroup, form: EzForm) => {
      if (control.getValue() && !reg.test(control.getValue())) {
        return { regex: error || `格式不正确` };
      }
      return null;
    };
    return fn;
  }

  static email(error: string = '邮箱格式不正确') {
    const fn = EzFormValidators.regex(REGEXP_EMAIL, error);
    return fn;
  }

  static phoneNumber(error: string = '手机号码格式不正确') {
    const fn = EzFormValidators.regex(REGEXP_PHONE_NUMBER, error);
    return fn;
  }

  static idCard(error: string = '身份证号码格式不正确') {
    const fn = EzFormValidators.regex(REGEXP_IDCARD, error);
    return fn;
  }
}
